//
//  graphicsMath.c
//  LAMapBasicDemo
//
//  Created by 罗亮富 on 2017/12/28.
//  Copyright © 2017年 2Bulu. All rights reserved.
//

#include "graphicsMath.h"
#include <math.h>
//生成bezier曲线控制点，使得*ctrP1、*ctrP2，p2三个控制点生成的bezier曲以p1、p2为端点
//p0:p1的前一个点 p1:bezier曲线起点 p2:bezier曲线终点, p3:p2的后一个点;smooth 取值0-1,0不平滑,1非常平滑;ctrP1,ctrP1生成的控制点
void CalculateBezierCurveControlPoints(float smooth_value, CGPoint p0, CGPoint p1, CGPoint p2, CGPoint p3, CGPoint *ctrP1, CGPoint *ctrP2)
{
    double xc1 = (p0.x + p1.x) /2.0;
    double yc1 = (p0.y + p1.y) /2.0;
    double xc2 = (p1.x + p2.x) /2.0;
    double yc2 = (p1.y + p2.y) /2.0;
    double xc3 = (p2.x + p3.x) /2.0;
    double yc3 = (p2.y + p3.y) /2.0;

    double len1 = sqrt((p1.x-p0.x) * (p1.x-p0.x) + (p1.y-p0.y) * (p1.y-p0.y));
    double len2 = sqrt((p2.x-p1.x) * (p2.x-p1.x) + (p2.y-p1.y) * (p2.y-p1.y));
    double len3 = sqrt((p3.x-p2.x) * (p3.x-p2.x) + (p3.y-p2.y) * (p3.y-p2.y));

    double k1 = len1 / (len1 + len2);
    double k2 = len2 / (len2 + len3);

    double xm1 = xc1 + (xc2 - xc1) * k1;
    double ym1 = yc1 + (yc2 - yc1) * k1;

    double xm2 = xc2 + (xc3 - xc2) * k2;
    double ym2 = yc2 + (yc3 - yc2) * k2;

    ctrP1->x = xm1 + (xc2 - xm1) * smooth_value + p1.x - xm1;
    ctrP1->y = ym1 + (yc2 - ym1) * smooth_value + p1.y - ym1;
    ctrP2->x = xm2 + (xc2 - xm2) * smooth_value + p2.x - xm2;
    ctrP2->y = ym2 + (yc2 - ym2) * smooth_value + p2.y - ym2;
}


#if IS_COCOA_PLAT
//p1:曲线起点  p2:曲线终点;smooth 取值0-1,0不平滑,1非常平滑 各点连接顺序 p0->p1->p2->p3,若p1是最前面的点，则前面的点取p1的值，同理若p3是最后的点,则后面的点取p3的值
inline void addSmoothBezierCurve(CGMutablePathRef path, float smooth, CGPoint p0, CGPoint p1, CGPoint p2, CGPoint p3)
{
    CGPoint ctrl1, ctrl2;
    CalculateBezierCurveControlPoints(smooth,p0,p1,p2,p3,&ctrl1,&ctrl2);
    CGPathAddCurveToPoint(path, NULL, ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, p2.x, p2.y);
    
}
#endif

